<template>
  <div class="file-manager">
    <!-- 文件夹路径导航 -->
    <el-row class="breadcrumb">
      <el-col :span="20">
        <el-breadcrumb>
          <!-- 返回上一级的按钮，添加间隙 -->
          <el-breadcrumb-item>
            <el-icon>
              <DArrowLeft/>
            </el-icon>
            <div style="display: inline-block; margin: 10px" @click="navigateUp(currentSrcPath)">
              返回上一级【{{ currentSrcPath.substring(currentSrcPath.indexOf('/') + 1) }}】
            </div>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>

    <!-- 文件/文件夹展示 -->
    <el-table
        :data="currentSrc"
        border
        max-height="350"
        size=small
        class="file-table"
        style="margin-bottom: 10px"
    >
      <el-table-column v-if="fileListUpdated" label="文件名" prop="filename">
        <template #default="{ row }">
          <div class="file-item">
            <!-- 文件夹图标 -->
            <el-icon v-if="row.is_dir" class="folder-icon" @click="handleEnter(row)">
              <Folder/>
            </el-icon>
            <!-- 文档的图标 -->
            <el-icon v-if="!row.is_dir" class="document-icon">
              <Document/>
            </el-icon>
            <!-- 文件名 -->
            <span v-if="row.is_dir" @click="handleEnter(row)">{{ row.filename }}</span>
            <span v-else>{{ row.filename }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="文件大小" prop="size"></el-table-column>
      <el-table-column label="最后修改时间" prop="last_modified"></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作">
        <template #default="{ row, $index }">
          <div class="file-actions">
            <el-button v-if="!row.is_dir" size="default" type="primary" @click="handleView(row)">查看</el-button>
            <el-button size="default" type="danger" @click="handleDelete(row, $index)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {ElBreadcrumb, ElBreadcrumbItem, ElButton, ElCol, ElMessage, ElRow} from 'element-plus';
import {DArrowLeft, Document, Folder} from '@element-plus/icons-vue';
import axios from "axios";
import EventBus from "@/utils/eventBus";

const globalApiUrl = import.meta.env.VITE_API_URL
let currentSrc = ref([]); // 当前目录下的文件列表
let currentSrcPath = ref("/"); // 当前文件夹路径
const getCurrentSrc = () => {
  const storedSrc = localStorage.getItem('srcFileList');
  currentSrcPath.value = localStorage.getItem('srcCurrentPath')
  if (storedSrc || storedSrc !== undefined) {
    currentSrc.value = JSON.parse(storedSrc);
  } else {
    currentSrc.value = []; // 如果没有数据，则初始化为空数组
  }
  fileListUpdated.value = true; // 设置数据更新状态为 true
}

const getFileList = async (str: string) => {
  try {
    const response = await axios.get(filesUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {path: str} // 传递当前路径
    });
    localStorage.setItem('srcFileList', JSON.stringify(response.data.data));
    localStorage.setItem('srcCurrentPath', str);
    currentSrc.value = response.data.data;
    fileListUpdated.value = true;
    currentSrcPath.value = str
  } catch (error) {
    console.error('Error fetching file list:', error);
    ElMessage.error('文件列表获取失败');
  }
};

let fileListUpdated = ref(false);
const filesUrl = globalApiUrl + '/files'; // 后端获取文件夹的 URL

// 当前查看的文件
const viewDialogVisible = ref(false);

// 删除文件
const handleDelete = async (file: any, index: number) => {
  // 访问后端路由删除文件，传递文件路径
  console.log(file.path);
  let str = file.path.substring(file.path.indexOf('/') + 1);
  try {
    const response = await axios.delete(filesUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {path: str} // 传递当前路径
    });
    if (response.data.result) {
      ElMessage.success('文件删除成功');
      await getFileList(currentSrcPath.value);
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('文件删除失败，请稍后重试');
  }
};

// 查看文件
const handleView = (file: any) => {
  if (!file.is_dir) {
    ElMessage.warning("暂不支持查看文件");
  }
  viewDialogVisible.value = true;
};
// 进入文件夹
const handleEnter = (row: any) => {
  let strPath = row.path.substring(row.path.indexOf('/') + 1);
  getFileList(strPath);
}

// 返回上一级
const navigateUp = (currentPath: any) => {
  // 在这里实现返回上一级的逻辑
  let count = currentPath.split('/').length - 1;
  if (count === 1) {
    ElMessage.warning("已经在源代码根目录了");
    return
  }
  let index = currentPath.lastIndexOf('/');
  if (index === -1) {
    return;
  }
  let strPath = currentPath.slice(0, index);
  getFileList(strPath);
};

const refreshData = () => {
  // 更新页面数据
  getCurrentSrc();
};

onMounted(() => {
  getCurrentSrc()
  EventBus.$on('update-src-data', refreshData);
});

</script>

<style scoped>
.file-manager {
  padding: 0px;
}

.breadcrumb {
  margin-top: 0px;
}

.file-actions {
  margin-top: 0px;
  display: flex;
  justify-content: space-between;
}

.file-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.folder-icon,
.document-icon {
  font-size: 20px;
  color: #409eff;
}

.el-table .el-table__body tr {
  border-bottom: 1px solid #e4e7ed;
}

.el-table-column--sortable .cell {
  padding: 0 !important;
}

/* 表格列宽控制 */
.el-table .el-table__body-wrapper {
  max-width: 100% !important;
}

/* 返回上一级按钮后添加间隙 */
.el-breadcrumb-item > el-icon {
  margin-right: 10px; /* 添加间隙 */
}

</style>